package com.eastfair.matching.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.api.GlobalBusinessServiceFeign;
import com.eastfair.auth.api.RoleServiceFeign;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.*;
import com.eastfair.auth.entity.Role;
import com.eastfair.auth.enumeration.OrganizationOrgTypeEnum;
import com.eastfair.auth.enumeration.OrganizationVestTypeEnum;
import com.eastfair.auth.enumeration.RoleRoleTypeEnum;
import com.eastfair.auth.exceptioncode.AuthServiceExceptionCode;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.jwt.service.JwtService;
import com.eastfair.matching.dto.BindComplementServiceProviderRoleDTO;
import com.eastfair.matching.dto.RemoveComplementServiceProviderRoleDTO;
import com.eastfair.matching.enumeration.MatchingExceptionCode;
import com.eastfair.matching.service.ComplementRegisterService;
import com.eastfair.matching.vo.ComplementRegisterDataVO;
import com.eastfair.venuebooking.api.ServiceProviderFeign;
import com.eastfair.venueservice.enumeration.ServiceProviderRoleEnum;
import com.eastfair.venueservice.enumeration.ServiceProviderTypeEnum;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 配套服务商注册
 * </p>
 *
 * @author lyw
 * @date 2022-07-20
 */
@Slf4j
@Service
public class ComplementRegisterServiceImpl implements ComplementRegisterService {

    @Autowired
    private UserAccountServiceFeign userAccountServiceFeign;
    @Autowired
    private AuthServiceFeign authServiceFeign;
    @Autowired
    private RoleServiceFeign roleServiceFeign;
    @Autowired
    private GlobalBusinessServiceFeign globalBusinessServiceFeign;
    @Autowired
    JwtService jwtService;
    @Autowired
    private ServiceProviderFeign serviceProviderFeign;

    /**
     * 配套服务商注册
     * @param userAccountDto
     * @return
     */
    @Override
    public ComplementRegisterDataVO registerSubSystemUser(UserAccountDto userAccountDto) {
        log.info("ComplementRegisterServiceImpl +++++ registerSubSystemUser - 配套服务商注册 params={}", JSONObject.toJSON(userAccountDto));
        R<UserAccountVo> r =userAccountServiceFeign.registerSubSystemUser(userAccountDto);
        if(!r.getIsSuccess()){
            throw BizException.wrap(r.getCode(),r.getMsg());
        }
        //查询配套服务商信息
        R<ServiceProviderVO> serviceProviderVOR = serviceProviderFeign.getByUserId(r.getData().getId(), ServiceProviderTypeEnum.MATCHING_SERVICE_PROVIDER.getCode());        //token解析对象
        if(!serviceProviderVOR.getIsSuccess()){
            throw BizException.wrap(serviceProviderVOR.getCode(),serviceProviderVOR.getMsg());
        }
        //注册后返回注册信息跟配套服务商聚合信息
      //  AuthInfo  authInfo = jwtService.parse(r.getData().getAuthInfo().getToken());
        //把对象放到上下文
      //  AutoInfoUtil.parseAuthInfoOfContextUtil(authInfo);
        return ComplementRegisterDataVO.builder().userAccountVo(r.getData()).serviceProviderVO(serviceProviderVOR.getData()).build();


    }

    /**
     * 配套服务商绑定角色.
     * @param bindComplementServiceProviderRoleDTO
     * @return
     */
    @Override
    public Boolean bindComplementServiceProviderRole(BindComplementServiceProviderRoleDTO bindComplementServiceProviderRoleDTO) {
        log.info("bindComplementServiceProviderRole - 配套服务商注册, params={}", bindComplementServiceProviderRoleDTO);
        RegisterDTO registerDTO = new RegisterDTO();
        //创建顶级组织
        OrganizationDTO organizationDTO = new OrganizationDTO();
        //组织类型  搭建商
        organizationDTO.setOrgType(OrganizationOrgTypeEnum.P_COMPOSITE_MATING);
        //资源
        organizationDTO.setVestType(OrganizationVestTypeEnum.R);
        organizationDTO.setParentId(BusinessConstant.parentId);
        //公司名称
        organizationDTO.setName(bindComplementServiceProviderRoleDTO.getServiceProviderName());
        registerDTO.setOrganizationDTO(organizationDTO);
        //创建用户角色
        RoleDTO role = new RoleDTO();
        role.setRoleType(RoleRoleTypeEnum.P_COMPOSITE_MATING_ADMIN);
        role.setName(ServiceProviderRoleEnum.MATCHING_COMMON_ROLE.getDesc());
        role.setBusinessTag(bindComplementServiceProviderRoleDTO.getServiceProviderRole());
        registerDTO.setRoleDTO(role);
        //修改关联信息
        UserAccountDto accountDto = new UserAccountDto();
        accountDto.setId(bindComplementServiceProviderRoleDTO.getUserId());
        //配套商id
        accountDto.setMatingId(bindComplementServiceProviderRoleDTO.getServiceProviderId());
        registerDTO.setUserAccountDto(accountDto);
        registerDTO.setTeamId(bindComplementServiceProviderRoleDTO.getServiceProviderId());
        log.info("registerDTO is {}", JSONObject.toJSONString(registerDTO));
        userAccountServiceFeign.registerServiceProvider(registerDTO);

        return Boolean.TRUE;
    }

    /**
     * 配套服务商移除角色
     * @param removeComplementServiceProviderRoleDTOList
     * @return
     */
    @Override
    public Boolean removeComplementServiceProviderRole(List<RemoveComplementServiceProviderRoleDTO> removeComplementServiceProviderRoleDTOList) {

        if(CollectionUtils.isEmpty(removeComplementServiceProviderRoleDTOList) || removeComplementServiceProviderRoleDTOList.size()==0){
            throw BizException.wrap(MatchingExceptionCode.NOT_SERVICE_PROVIDER_NULL);
        }
        removeComplementServiceProviderRoleDTOList.forEach((s)->{
            ContextUtil.setTeamId(s.getServiceProviderId());
            //查询基础角色信息
            RoleDTO roleDTO =new RoleDTO();
            roleDTO.setBusinessTag(s.getServiceProviderRole());
            R<List<RoleVo>> queryRole = roleServiceFeign.queryRole(roleDTO);
            if(!queryRole.getIsSuccess()){
                throw BizException.wrap(queryRole.getCode(),queryRole.getMsg());
            }

            //角色id集合
            List<Long> roleIds= Lists.newArrayList();
            List<Long> ids = queryRole.getData().stream().map(RoleVo::getId).collect(Collectors.toList());
            roleIds.addAll(ids);
            List<Long> userIds = Lists.newArrayList();
            userIds.add(s.getUserId());
            UserRoleDto userRoleDto =new UserRoleDto();
            userRoleDto.setRoleIds(roleIds);
            userRoleDto.setUserIds(userIds);
            authServiceFeign.removeOrgRole(userRoleDto);
        });
        return Boolean.TRUE;
    }
}
